/**
 * @file   date_time.cpp
 * @brief  日期时间相关
 * @encode UTF-8
 * @log    date        author      notes
 *         2021.09.17  Jimmy       first version
 */
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <chrono>
#include <sys/time.h>
#include <memory.h>

#include "date_time.h"


/**
 * @brief  Get the Current Tick object
 * @return TimeStamp 
 * @author Jimmy 
 * @date   2021.09.17
 */
TimeStamp getCurrentTick()
{
    /**
     * std::chrono::steady_clock::now() 表示随系统启动到现在的时间片
     */
    auto tp      = std::chrono::steady_clock::now();
    auto curTime = std::chrono::duration_cast<std::chrono::microseconds>(tp.time_since_epoch()).count();
    return curTime;
}

/**
 * @brief  Get the System Running Time Sec object
 * @return TimeStamp 
 * @author Jimmy 
 * @date   2021.09.17
 */
TimeStamp getSystemRunningTimeSec()
{
    auto tp      = std::chrono::steady_clock::now();
    auto curTime = std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch()).count();
    return curTime;
}

/**
 * @brief  Get the Real Time Clock Micro Sec object
 * @return TimeStamp 
 * @author Jimmy 
 * @date   2021.09.17
 */
TimeStamp getRealTimeClockMicroSec()
{
    auto tp      = std::chrono::system_clock::now();
    auto curTime = std::chrono::duration_cast<std::chrono::microseconds>(tp.time_since_epoch()).count();
    return curTime;
}

/**
 * @brief  Construct a new Time Interval:: Time Interval object
 * @author Jimmy 
 * @date   2021.09.17
 */
TimeInterval::TimeInterval()
{
    mIntervalMax = mIntervalMin = mIntervalLast = 0;

    for (auto i = 0; i < MAX_AVERAGE_CNT; i ++)
    {
        mIntervalLastList[i] = 0;
    }

    mIndex = 0;
    mIntervalMax = 1000 * 1000 * 1000;
    mIntervalMin = 0;
    mIntervalLast = mark();
}

/**
 * @brief  Destroy the Time Interval:: Time Interval object
 * @author Jimmy 
 * @date   2021.09.17
 */
TimeInterval::~TimeInterval()
{

}

/**
 * @brief  计时开始
 * @return TimeStamp 
 * @author Jimmy 
 * @date   2021.09.17
 */
TimeStamp TimeInterval::mark()
{
    mLastTime = getCurrentTick();
    return mLastTime;
}

/**
 * @brief  计时结束
 * @return TimeStamp 
 * @author Jimmy 
 * @date   2021.09.17
 */
TimeStamp TimeInterval::interval()
{
    return update();
}

/**
 * @brief  update
 * @return TimeStamp 
 * @author Jimmy 
 * @date   2021.09.17
 */
TimeStamp TimeInterval::update()
{
    TimeStamp curTick = getCurrentTick();

    mIntervalLast = curTick - mLastTime;
    mLastTime = curTick;
    mIntervalLastList[mIndex ++] = mIntervalLast;

    if (mIndex >= MAX_AVERAGE_CNT)
    {
        mIndex = 0;
    }

    if (mIntervalLast > mIntervalMax)
    {
        mIntervalMax = mIntervalLast;
    }

    if (mIntervalLast < mIntervalMin)
    {
        mIntervalMin = mIntervalLast;
    }

    return mIntervalLast;
}


/* End of file */
